/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.exception.handle;

import java.util.Date;
import java.util.Locale;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.ext.ExceptionMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.common.utils.bean.ExceptionUtils;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.common.utils.exception.InterSystemExceptionSpec;
import com.foreveross.bsl.common.utils.exception.RemoteInvokeException;
import com.foreveross.bsl.common.utils.mapper.JsonMapper;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-7-22
 *
 */
public class CxfExceptionMapper implements ExceptionMapper<Throwable> {

	private Logger log = LoggerFactory.getLogger(CxfExceptionMapper.class);
	
	private String systemName="[no-set]";
	private JsonMapper jsonMapper=JsonMapper.nonEmptyMapper();

	@Override
	public Response toResponse(Throwable e) {
		ResponseBuilder rb = Response.status(Response.Status.INTERNAL_SERVER_ERROR);  
		RemoteInvokeException re=null;
		if(e instanceof RemoteInvokeException){
			log.error(e.getMessage(), e);
			//如果是远程调用异常
			re=(RemoteInvokeException)e;
			re.getExceptionSpec().putSystem(systemName);
		} else {
			String msg=ExceptionUtils.formatException(e); // 添加异常码对应设置i18n国际化文件夹中/META-INF/i18n
			InterSystemExceptionSpec spec=null;
			Date exceptionTime=new Date();
			log.error(e.getMessage(), e);
			if(e instanceof ApplicationException){
				ApplicationException a = (ApplicationException)e;
				spec=new InterSystemExceptionSpec(systemName, a.getCode(), msg, exceptionTime);
			}
			else{
				spec=new InterSystemExceptionSpec(systemName, msg, exceptionTime);
			}
			re=new RemoteInvokeException(spec);
		}
		rb.entity(jsonMapper.toJson(re.getExceptionSpec()));  
		rb.type("text/x-json;charset=UTF-8");  
		rb.language(Locale.SIMPLIFIED_CHINESE);  
		Response r = rb.build();  
		return r; 
	}

	/**
	 * @return the systemName
	 */
	public String getSystemName() {
		return systemName;
	}

	/**
	 * @param systemName the systemName to set
	 */
	public void setSystemName(String systemName) {
		this.systemName = systemName;
	}
	
}
